import COS from 'cos-js-sdk-v5'
import constant from './constant'
let Utils = function (){
    return {
        formatDate(value, fmt, emptyText) {
            fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
            if(!value) return emptyText || ""
            let getDate = new Date(value)
            let o = {
            'M+': getDate.getMonth() + 1,
            'd+': getDate.getDate(),
            'h+': getDate.getHours(),
            'm+': getDate.getMinutes(),
            's+': getDate.getSeconds(),
            'q+': Math.floor((getDate.getMonth() + 3) / 3),
            'S': getDate.getMilliseconds()
            };
            if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
            }
            for (let k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
            }
            }
            return fmt;
        },
        tel(tel){
            if(isNaN(tel)) return
            window.location.href = 'tel://'+tel
        },
        imgError(type){
            if(type == constant.IDENTITY.MARCHANT){
                event.target.src = require('@/assets/img/avatar_business.png')
            }else{
                event.target.src = require('@/assets/img/avatar_zb.png')
            }
        },
        imgFit(event){
            let pw = event.currentTarget.parentNode.offsetWidth
            let ph = event.currentTarget.parentNode.offsetHeight
            let w = event.target.width
            let h = event.target.height
            let className = w/pw >= h/ph ? 'w' : 'h'
            event.target.className = className
        },
        GetExtensionFileName(pathfilename) {
          var reg = /(\\+)/g;
          var pString = pathfilename.replace(reg, "#"); //用正则表达式来将\或\\替换成#
          var arr = pString.split("#"); // 以“#”为分隔符，将字符分解为数组 例如 D Program Files bg.png
          var lastString = arr[arr.length - 1]; //取最后一个字符
          var arr2 = lastString.split("."); //   再以"."作为分隔符
          return arr2[arr2.length - 1]; //将后缀名返回出来
        },
        /**
         * 上传文件通用方法
         * file 文件对象---也可以是自定义对象(自定义对象的上传内容为file.html)
         * path 文件上传路径
         * item 上传图片后回显对应的Key
         */
        async doUpload(file, path, target, key, validateTarget, reName){
          let nowTime = new Date().getTime()
          let TMPCOSKEY = localStorage.getItem('TMPCOSKEY')
          if(TMPCOSKEY){
            TMPCOSKEY = JSON.parse(TMPCOSKEY)
          }
          if(!TMPCOSKEY || TMPCOSKEY.expiredTime * 1000 <= nowTime){
            let result = await this.getAuthorization()
            console.log('重新获取临时秘钥=>', result)
            TMPCOSKEY = typeof(result.data) == 'string' ? JSON.parse(result.data) : result.data
            localStorage.setItem('TMPCOSKEY',JSON.stringify(TMPCOSKEY))
          }
          let credentials = TMPCOSKEY && TMPCOSKEY.credentials
          let cos = new COS({
            SecretId: credentials.tmpSecretId,
            SecretKey: credentials.tmpSecretKey,
            XCosSecurityToken: credentials.sessionToken,
          });
          console.log('cos=>', cos)
          let fileName = reName || (file.size ? path + '/' + new Date().getTime() + '.' + this.GetExtensionFileName(file.name) : path + '/' + file.name)
          cos.putObject({
            Bucket: constant.COS.Bucket, /* 必须 */
            Region: constant.COS.Region,     /* 存储桶所在地域，必须字段 */
            Key: fileName,              /* 必须 */
            StorageClass: 'STANDARD',
            Body: file.html || file, // 上传文件对象
            onProgress: function(progressData) {
                console.log('progressData', JSON.stringify(progressData));
            }
          }, function(err, data) {
              console.log('err=>', err);
              console.log('data=>', data);
              if(target && key){
                target[key] = 'https://' + data.Location
              }
              if(validateTarget && key){
                validateTarget.validateField(key)
              }
          });
        },
        /**
         * 获取临时秘钥
         */
        getAuthorization(){
          return vm.sendAxiosPromise({
            url: vm.ApiSet.cosdTempKey,
          })
        },
        getfilesize(size) {
          if (!size)
            return "";
          var num = 1024.00; //byte
          if (size < num)
            return size + "B";
          if (size < Math.pow(num, 2))
            return (size / num).toFixed(2) + "K"; //kb
          if (size < Math.pow(num, 3))
            return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
          if (size < Math.pow(num, 4))
            return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
          return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
        },
        getListData(data, config) {
          var id = config.id || 'id';
          var pid = config.pid || 'pid';
          var children = config.children || 'children';
          // var label=config.label || 'LctnName';
          var idMap = {};
          var jsonTree = [];
          data.forEach(function (v) {
              idMap[v[id]] = v;
          });
          data.forEach(function (v) {
            var parent = idMap[v[pid]];
            if (parent) {
              !parent[children] && (parent[children] = []);
              parent[children].push(v);
            } else {
              jsonTree.push(v);
            }
          });
          return jsonTree;
        },
        secondToDate(result, disSecond) {
          var h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
          var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
          var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
          let timeFn = ""
          if (!isNaN(h) && Number(h) > 0) {
            timeFn = timeFn + h + "小时 "
          }
          if (!isNaN(m) && Number(m) > 0) {
            timeFn = timeFn + m + (disSecond ? "分钟 " : "分 ")
          }
          if (!isNaN(s) && Number(s) > 0 && !disSecond) {
            timeFn = timeFn + s + "秒"
          }
          return timeFn;
        },
        toY(value, fixed){
          if(!value || isNaN(value)){
            return 0
          }
          let isMinus = false
          let param = {};
          let k = 10000,
          sizes = ['', '万', '亿', '万亿'],
          i;
          if(value < 0){
            isMinus = true
            value = -value
          }
          if(value < k){
            param.value = value
            param.unit=''
          }else{
            i = Math.floor(Math.log(value) / Math.log(k)); 
            param.value = value / Math.pow(k, i);
            param.unit = sizes[i];
          }
          if(param.value && param.value.toString().split('.')[1] && param.value.toString().split('.')[1].length > fixed){
            param.value = Number(param.value).toFixed(fixed)
          }
          if(isMinus){
            return -param.value + param.unit;
          }
          return param.value + param.unit;
        },
    }
}();
export default Utils;
